package org.v2ray.rocket.proxy.support.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewbinding.ViewBinding
import kotlinx.coroutines.launch
import org.v2ray.rocket.proxy.support.base.mvi.MviEffect
import org.v2ray.rocket.proxy.support.base.mvi.MviIntent
import org.v2ray.rocket.proxy.support.base.mvi.MviState

/**
 * MVI架构的基础Fragment
 * @param VB ViewBinding类型
 * @param I Intent类型
 * @param S State类型
 * @param E Effect类型
 * @param VM ViewModel类型
 */
abstract class BaseFragment<VB : ViewBinding, I : MviIntent, S : MviState, E : MviEffect, VM : BaseViewModel<I, S, E>> : Fragment() {
    
    private var _binding: VB? = null
    protected val binding get() = _binding!!
    
    protected abstract val viewModel: VM
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = getViewBinding(inflater, container)
        return binding.root
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        initView()
        initObservers()
        initData()
    }
    
    /**
     * 获取ViewBinding
     */
    abstract fun getViewBinding(inflater: LayoutInflater, container: ViewGroup?): VB
    
    /**
     * 初始化视图
     */
    abstract fun initView()
    
    /**
     * 初始化数据
     */
    abstract fun initData()
    
    /**
     * 初始化观察者
     */
    private fun initObservers() {
        viewLifecycleOwner.lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                // 观察状态变化
                launch {
                    viewModel.viewState.collect { state ->
                        renderState(state)
                    }
                }
                
                // 观察一次性事件
                launch {
                    viewModel.effect.collect { effect ->
                        renderEffect(effect)
                    }
                }
            }
        }
    }
    
    /**
     * 渲染状态
     */
    abstract fun renderState(state: S)
    
    /**
     * 渲染一次性事件
     */
    abstract fun renderEffect(effect: E)
    
    /**
     * 发送Intent
     */
    protected fun setIntent(intent: I) {
        viewModel.setIntent(intent)
    }
    
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 